import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class NestedSearchScrollPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (context, innerBoxIsScrolled) {
          return [
            // 1. 标题栏
            SliverAppBar(
              pinned: true,
              expandedHeight: 200.0,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('NestedScrollView 示例'),
                background: Image.network(
                  'https://picsum.photos/600/300',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            // 2. 搜索框（固定在标题栏下方）
            SliverPersistentHeader(
              pinned: true, // 固定在顶部
              delegate: _SearchBoxDelegate(),
            ),
          ];
        },
        body: ListView.builder(
          itemCount: 50,
          itemBuilder: (context, index) => ListTile(
            title: Text('列表项 ${index + 1}'),
            subtitle: Text('搜索框已固定'),
          ),
        ),
      ),
    );
  }
}

// 自定义搜索框 Delegate
class _SearchBoxDelegate extends SliverPersistentHeaderDelegate {
  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
      child: TextField(
        decoration: InputDecoration(
          hintText: '搜索内容...',
          prefixIcon: Icon(Icons.search),
          border: OutlineInputBorder(),
        ),
      ),
    );
  }

  @override
  double get maxExtent => 60.0; // 搜索框最大高度
  @override
  double get minExtent => 60.0; // 搜索框最小高度（固定高度）
  @override
  bool shouldRebuild(covariant _SearchBoxDelegate oldDelegate) => false;
}
